<template>
  <div id="chat">
    <badge class="online-cnt" :num="'当前在线: '+ onlineCnt "></badge>
    <!-- S 消息区域 -->
    <scroll class="msgs" style="top: 0;bottom:45px;">
      <template v-for="(message,index) in messages">
        <msg v-on:grap="grapRedPacket" v-bind="message" :key="index"></msg>
      </template>
    </scroll>
    <!-- E 消息区域 -->

    <!-- S 功能区域 -->
    <div class="bottom-div">
      <!-- <von-input type="text" v-model="chatText" placeholder="来一起BB起来吧"></von-input> -->
      <div class="form">
        <div class="input">
          <input v-model="chatText" placeholder="输入聊天内容...">
        </div>
        <!-- focus 监听输入内容加 highlighte-->
        <button class="btn-cmt-send" @click="send">
          <span>发 表</span>
        </button>
      </div>
      <img :src="STATIC_PIC_PTH.redPacket" @click="sendRedPacket" class="send-btn">
      <img :src="STATIC_PIC_PTH.gift" @click="showGift = true" class="send-btn">
    </div>
    <!-- E 功能区域 -->

    <!-- S 红包模块 -->
    <transition name="slideInUp">
      <red-pack ref="redPack"></red-pack>
    </transition>
    <!-- E 红包模块 -->

    <transition name="slideInUp">
      <!-- 打赏模块 -->
      <gift ref="gift" v-show="showGift" @hideGift="showGift = false"></gift>
    </transition>
  </div>
</template>
<script>
  import {
    mapGetters
  } from 'vuex'
  import msg from "components/chat/msgBox";
  import {
    END_POINT,
    STATIC_PIC_PTH
  } from "tools/config";
  import redPack from "components/redPack/redPack"; // 红包模块
  import gift from "components/gift/gift"; // 红包模块
  import './chat.scss'

  export default {
    name: "",
    components: {
      msg,
      gift,
      redPack
    },
    data() {
      return {
        messages: [],
        chatText: "",
        invokeIdCnt: 0,
        STATIC_PIC_PTH,
        isConnected: false, //是否连接聊天服务器
        onlineCnt: 1,
        showGift:false, //是否打开打赏面板
      };
    },
    mounted() {
      this.sendDanmu = this.$start(document.querySelector('#danmu-pannel'), [0, 0.5]);
      let that = this;
      this.messages.push({
        level: false,
        creator: "系统消息",
        msgBody: "连接中..."
      });
      this.connectSrv();
    },
    computed: {
      ...mapGetters([
        'userInfo',
        'videoInfo',
      ])
    },
    methods: {
      // 发红包
      sendRedPacket() {
        this.$refs.redPack.showStatus = 8
      },
      // 聊天服务器连接成功
      onConnected(frame) {
        this.isConnected = true;
        this.messages.pop();
        this.messages.push({
          level: false,
          creator: "系统消息",
          msgBody: "连接成功！"
        });
        // 订阅聊天信息频道
        this.$stompClient.subscribe(
          "/topic/getResponse/" + this.videoInfo.id,
          this.responseCallback,
          this.onFailed
        );
        // 订阅在线人数频道
        this.$stompClient.subscribe(
          "/topic/online_user/" + this.videoInfo.id,
          this.receiveOnlineCnt, {
            userId: this.userInfo.id,
            roomId: this.videoInfo.id
          }
        );
      },
      onFailed(frame) {
        if (!this.isConnected) {
          return;
        }
        this.isConnected = false;
        this.messages.push({
          level: false,
          creator: "系统消息",
          msgBody: "聊天服务器连接失败"
        });
        this.disconnect()
      },
      connectSrv() {
        let headers = {
          userId: this.userInfo.id,
          roomId: this.videoInfo.id,
        };
        this.connetWM(END_POINT, headers, this.onConnected, this.onFailed);
      },
      //发送聊天信息
      send() {
        if (!this.isConnected) {
          $toast.show("聊天服务器未连接,消息无法发送!");
          return;
        }
        let destination = "/welcome";
        let invokeId = this.getInvokeId();
        //封装消息体
        let body = {
          userId: this.userInfo.id,
          roomId: this.videoInfo.id,
          name: this.userInfo.name,
          content: this.chatText,
        }
        this.chatText = "";
        this.sendWM(destination, JSON.stringify(body), invokeId, this.responseCallback, 3000);
      },
      responseCallback(frame) {
        console.log("responseCallback msg=>" + frame.body);
        let invokeId = frame.body.substr(0, 4);
        this.removeStompMonitor(invokeId);

        let arrMsg = JSON.parse(frame.body);
        if (typeof arrMsg === 'object') {
          //消息
          this.messages.push({
            level: 1,
            creator: arrMsg.name,
            msgType: arrMsg.type,
            msgBody: arrMsg.content
          });
          //弹幕
          if (arrMsg.type === 'string') {
            this.sendDanmu({
              text: arrMsg.content,
              color: '#fff',
              speed: 2,
              classname: 'style1'
            });
          }
        }
      },
      //断开连接
      disconnect() {
        this.disconnetWM();
      },
      //   接收到在线人数
      receiveOnlineCnt(frame) {
        this.onlineCnt = Number(frame.body) || 1;
      },
      grapRedPacket(msgBody) {
        this.$refs.redPack.queryPacketStatus(msgBody);
      },
      getInvokeId() {
        let hex = (this.invokeIdCnt++).toString(16);
        let zero = "0000";
        let tmp = 4 - hex.length;
        return zero.substr(0, tmp) + hex;
      },
    },
    stompClient: {
      monitorIntervalTime: 10000,
      stompReconnect: true,
      timeout(orgCmd) {},
      errorCallback() {
        console.error('连接失败')
      }
    }
  };

</script>
